import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import VueAxios from 'vue-axios'
import fa from "element-ui/src/locale/lang/fa";

Vue.use(VueAxios, axios)

Vue.use(ElementUI);


Vue.config.productionTip = false
let flag = false
router.beforeEach((to, from, next) => {
  //导航卫士,在这里面进行路由的拼接
  let uid  = 3
  if(store.state.user!=null){
    uid=store.state.user.id
  }
  // debugger

  if(localStorage.getItem("uid")!=null){
    uid=localStorage.getItem("uid")
  }else {

  }
  console.log("用户id:"+uid)



  //进入主界面的时候
  if (to.path == '/home') {
      madeRouters(uid,next);
  } else {
    next();
  }

  if(window.performance.navigation.type == 1) {
    location.href = "/home"

    madeRouters(uid, next);
  }
})




function madeRouters(uid,next,flag) {
  //发送请求获取 当前用户的的menu资源
  axios.get('http://localhost:9001/menu/findMenuByUid', {
    params: {
      uid: uid
    }
  }).then((response) => {
    //获取menu资源
    let menus = response.data;
    //考虑把这个menus资源转换成我们的路由对象
    let menuRouters = setRouter(menus);
    console.log("**********"+JSON.stringify(menuRouters))
    //赋值给路由的home中的children
    router.options.routes[0].children = menuRouters;
    //加入到路由中
    router.addRoutes(router.options.routes);
    next({path: '/common'});
  });
}

function setRouter(menus) {
  let menuRouters = [];
  //先转换一级菜单资源
  for (let i = 0; i < menus.length; i++) {

    let menu = menus[i];

    let children = [];
    //递归处理
    if (menu.children && menu.children instanceof Array) {
      children = setRouter(menu.children);
    }
    //拼接孩子的操作节点
    let oper = children.map((x)=>x.path).join(",");
    //创建路由对象
    let newRouter = {
      path: menu.path,
      name: menu.label,
      iconCls: menu.iconCls,
      children: children,
      oper:oper
    }
    //获取组件名称
    let componentName = menu.component;
    //组件
    newRouter.component = () => import('./views/' + componentName + '.vue');
    //放入到menuRouters
    menuRouters.push(newRouter);
  }
  return menuRouters;
}
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
